package com.kaiwukj.android.ufamily.mvp.ui.page.home.message;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.mvp.http.entity.base.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

public class MessageListAdapter extends BaseMultiItemQuickAdapter<MessageMultiItemEntity, BaseViewHolder> {

    private ChatListAdapter mChatAdapter;

    public MessageListAdapter() {
        super(new ArrayList<>());
        addItemType(MessageMultiItemEntity.KEEPER, R.layout.item_chat_keeper);
        addItemType(MessageMultiItemEntity.MSG_NOTICE, R.layout.item_dynamic_about);
        addItemType(MessageMultiItemEntity.CHAT, R.layout.widget_list_base);
        // addItemType(MessageMultiItemEntity.CHAT_GROUP, R.layout.widget_list_base);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, MessageMultiItemEntity item, @NotNull List<?> payloads) {
//        /super.convert(holder, item, payloads);
        if (payloads.isEmpty()) {
            convert(holder, item);
        } else {
            String tag = (String) payloads.get(0);
            if ("keeper".equals(tag)) {
                if (item.getItemType() == MessageMultiItemEntity.KEEPER) {
                    TextView tvDesc = holder.getView(R.id.tv_desc);
                    TextView tvUnReadCount = holder.getView(R.id.unread_msg_number);
                    EMConversation keeperConversation = item.getKeeperConversation();
                    if (keeperConversation != null) {
                        tvDesc.setText(EaseCommonUtils.getMessageDigest(keeperConversation.getLastMessage(), getContext()));
                        if (keeperConversation.getUnreadMsgCount() > 0) {
                            tvUnReadCount.setVisibility(View.VISIBLE);
                            tvUnReadCount.setText(String.valueOf(keeperConversation.getUnreadMsgCount()));
                        } else {
                            tvUnReadCount.setVisibility(View.GONE);
                            tvUnReadCount.setText(String.valueOf(0));
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void convert(@NotNull BaseViewHolder helper, MessageMultiItemEntity item) {
        switch (item.getItemType()) {
            case MessageMultiItemEntity.KEEPER:
                ImageView ivAvatar = helper.getView(R.id.iv_image);
                TextView tvDesc = helper.getView(R.id.tv_desc);
                TextView tvUnReadCount = helper.getView(R.id.unread_msg_number);
                EMConversation keeperConversation = item.getKeeperConversation();
                if (keeperConversation != null) {
                    tvDesc.setText(EaseCommonUtils.getMessageDigest(keeperConversation.getLastMessage(), getContext()));
                    if (keeperConversation.getUnreadMsgCount() > 0) {
                        tvUnReadCount.setVisibility(View.VISIBLE);
                        tvUnReadCount.setText(String.valueOf(keeperConversation.getUnreadMsgCount()));
                    } else {
                        tvUnReadCount.setVisibility(View.GONE);
                        tvUnReadCount.setText(String.valueOf(0));
                    }
                }
                Glide.with(getContext())
                        // .load("http://jylqntest.kaiwumace.com/4e35289e-ae20-43a5-9364-fccad17b4277.jpg")
                        .load(R.mipmap.ic_chat_keeper_avatar_pre)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(ivAvatar);
                helper.itemView.setOnClickListener(v -> {
                    if (mOnEventListener != null) mOnEventListener.onKeeperClick(helper.itemView);
                    if (keeperConversation != null) {
                        keeperConversation.markAllMessagesAsRead();
                        tvUnReadCount.setVisibility(View.GONE);
                        tvUnReadCount.setText(String.valueOf(0));
                    }
                });
                break;
            case MessageMultiItemEntity.MSG_NOTICE:
                helper.itemView.setOnClickListener(v -> {
                    if (mOnEventListener != null) mOnEventListener.onAboutMeClick(helper.itemView);
                });
                break;
            case MessageMultiItemEntity.CHAT:
                RecyclerView rvChat = helper.getView(R.id.rv_list);
                rvChat.setLayoutManager(new LinearLayoutManager(getContext()));
                mChatAdapter = new ChatListAdapter(item.getChatList());
                rvChat.setAdapter(mChatAdapter);
                mChatAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    mChatAdapter.closeSwipe();
                    if (view.getId() == R.id.tv_delete) {
                        //UToast.showShort(getContext(), "delete");
                        EMClient.getInstance().chatManager().deleteConversation(mChatAdapter.getItem(position).conversationId(), false);
                        mChatAdapter.removeAt(position);
                    } else if (view.getId() == R.id.container_item) {
                        EMConversation conversation = mChatAdapter.getItem(position);
                        String conversationId = conversation.conversationId();
                        //   UserCacheInfo info = UserCacheManager.get(conversationId);
                        if (!EMClient.getInstance().isConnected()) {
                            ToastUtils.showShort("未连接到聊天服务器");
                        } else if (conversationId.equals(EMClient.getInstance().getCurrentUser()))
                            ToastUtils.showShort(R.string.Cant_chat_with_yourself);
                        else {

                            if (conversation.isGroup()) {
                                ChatActivity.startGroupChat(getContext(), conversationId);
                            } else {
                                ChatActivity.startSingleChat(getContext(), conversationId);
                            }

                            conversation.markAllMessagesAsRead();
                            EventBus.getDefault().post(new EventMessage("chat_count"));
                            mChatAdapter.setData(position, conversation);
                        }
                    }
                });

                break;

        }
    }

    public void refreshKeeperChat() {
        notifyItemChanged(0, "keeper");
    }

    public void addChatData(List<EMConversation> data, boolean isRefresh) {
        if (mChatAdapter != null) {
            if (isRefresh) {
                mChatAdapter.setList(data);
            } else {
                mChatAdapter.addData(data);
            }
        }
    }

    private OnEventListener mOnEventListener;

    public void setOnEventListener(OnEventListener eventListener) {
        mOnEventListener = eventListener;
    }

    public interface OnEventListener {
        void onKeeperClick(View view);

        void onAboutMeClick(View view);
    }
}
